import { useEffect, useState } from "react";
import { useModel } from "umi";
import { Button, Checkbox, message, Form, Select, Space, Input } from "antd";
import { useReactive } from "ahooks";
import { v4 as uuidv4 } from "uuid";

import useAllMembers from "../../hooks/member/useAllMembers";
import useAddMember from "../../hooks/institution/useAddMember";

const AddInstitutionMember = ({ institution, institutionMembers, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loading: membersLoading, members } = useAllMembers();
    const { addInstitutionMember } = useAddMember();

    const [form] = Form.useForm();

    const state = useReactive({
        bntloading: false,
        selectedMember: [],
    });

    useEffect(() => {
        form.resetFields();
    }, [institution]);

    const onStaffChange = (value, option) => {
        state.selectedMember = option;
    };

    const onFinish = async (values) => {
        let index = institutionMembers.findIndex((item) => item.omUuid === state.selectedMember.omUuid);
        if (index >= 0) return message.warning("该成员已经在该机构下了，不能重复添加");
        state.bntloading = true;
        let data = {
            reUuid: uuidv4(),
            oiUuid: institution.oiUuid,
            reType: state.selectedMember.omIfim === true ? "内部" : "外部",
            osUuid: null,
            omUuid: state.selectedMember.omUuid || null,
            oimRemk: values.oimRemk,
        };
        await addInstitutionMember(data, () => {
            reloadData();
            form.resetFields();
            onCloseGlobalModal();
        });
        state.bntloading = false;
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item label="人员" name="osUuid" rules={[{ required: true }]}>
                <Select
                    allowClear
                    placeholder="请选择"
                    loading={membersLoading}
                    options={members.filter((item) => institutionMembers.findIndex((_item) => _item.omUuid === item.omUuid) === -1)}
                    fieldNames={{ label: "omName", value: "omUuid" }}
                    onChange={onStaffChange}
                />
            </Form.Item>

            <Form.Item label="角色" name="oimRemk" rules={[{ required: true }]}>
                <Input allowClear placeholder="请输入" />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.bntloading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.bntloading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default AddInstitutionMember;
